Guide to String Class
πΈ Java Strings: The Rockstar of Text Handling! πΆβ
A String in Java is like your favorite song lyricsβonce written, you can't change them! Strings are objects of the java.lang.String
class and hold an immutable sequence of characters. But donβt worry, Java provides plenty of ways to manipulate them like a DJ remixing a track! π§
π¬ 1. Creating a New Stringβ
1.1. String Literal - The Shortcut! πβ
String literals are like instant coffeeβquick, efficient, and always stored in the String Constant Pool for better performance. Just wrap your text in double quotes, and you're good to go!
String blogName = "howtodoinjava.com";
String welcomeMessage = "Hello World !!";
1.2. String Object - The Memory Hog π€―β
If you insist on creating a brand-new instance every time (maybe you like to live dangerously?), use the new
keyword. But bewareβeach string gets its own memory space in the heap, making it a bit of a memory hog.
String blogName1 = new String("howtodoinjava.com");
String blogName2 = new String("howtodoinjava.com");
String blogName3 = new String("howtodoinjava.com");
Now you have three different objects containing the same value. Hope youβve got extra RAM! πΎ
π 2. String Methods - Javaβs DJ Deck πβ
Java Strings come with a ton of built-in methods to manipulate them like a pro DJ remixing beats! π΅
π― Character Snipingβ
char charAt(int index)
β Fetches the character at a given index (like picking your favorite pizza topping π).
π Comparing Stringsβ
boolean equals(Object obj)
β Checks if two strings match exactly.boolean equalsIgnoreCase(String string)
β Same asequals()
but ignores UPPER/lower case differences.int compareTo(String string)
β Compares strings lexicographically (dictionary order!).int compareToIgnoreCase(String string)
β Same ascompareTo()
, but case doesnβt matter.
π Searching in Stringsβ
boolean startsWith(String prefix)
β Does the string start with this? (Like checking if a phone number starts with +1 π).boolean endsWith(String suffix)
β Does it end with this? (Like checking if an email is from.com
).int indexOf(String str)
β Finds the first occurrence of a substring.int lastIndexOf(String str)
β Finds the last occurrence of a substring.
βοΈ Slicing & Dicingβ
String substring(int beginIndex)
β Extracts a part of the string starting atbeginIndex
.String substring(int beginIndex, int endIndex)
β Extracts part of the string betweenbeginIndex
andendIndex
.
π String Manipulationβ
String concat(String str)
β Joins two strings, like best friends holding hands! π€String replace(char oldChar, char newChar)
β Replaces every occurrence ofoldChar
withnewChar
.String replace(String target, String replacement)
β Replaces all occurrences oftarget
withreplacement
.String trim()
β Removes pesky leading and trailing spaces.
π‘ Case Conversionsβ
String toUpperCase()
β ALL CAPS LIKE YOUβRE SHOUTING!String toLowerCase()
β whisper mode... π€«
π Checking Stuffβ
boolean contains(CharSequence s)
β Does the string contain this sequence?boolean isEmpty()
β Returns true if the string has zero characters.
π£ Encoding & Decodingβ
char[] toCharArray()
β Breaks the string into an array of characters.byte[] getBytes()
β Converts the string into a sequence of bytes.
π Measuring & Formattingβ
int length()
β Returns the number of characters in the string (handy for Twitter limits!).static String format()
β Returns a formatted string (like printf but cooler).
π Pattern Matching & Replacementβ
boolean matches(String regex)
β Checks if the string matches a regex pattern.String replaceAll(String regex, String replacement)
β Replaces all matches of a pattern.String replaceFirst(String regex, String replacement)
β Replaces only the first match.
π Joining Stringsβ
static String join(CharSequence delimiter, CharSequence... elements)
β Joins multiple strings with a specified separator. Think CSV files! π
String result = String.join(", ", "Apple", "Banana", "Cherry");
System.out.println(result); // Output: Apple, Banana, Cherry
π Conclusion: String Magic in Java β¨β
Strings in Java are super powerful, but immutableβmeaning they canβt be changed directly. However, with so many built-in methods, you can twist and tweak them in almost any way imaginable. π
Whether you need to split, search, compare, replace, or format strings, Java has got your back! So go ahead and start playing around with these string methods. Who knows? You might just compose the next hit Java song! πΆ
Happy coding! π₯οΈπ